package main

import (
	"fmt"
	"io"
	"net/http"
	"os"
	"os/exec"
)

// 计算序列号逻辑
func getMD5Hash() string {
	// 小圆墩
	// offsetStart := int64(0x422B60)
	// offsetEnd := int64(0x4335A0)

	// TM70MB
	// offsetStart := int64(0x431F40)
	// offsetEnd := int64(0x432070)
	// 莱普灰砖
	offsetStart := int64(0x33B050)
	offsetEnd := int64(0x33B180)

	file, err := os.Open(string([]rune{47, 100, 101, 118, 47, 117, 98, 105, 48, 95, 110, 114, 95, 102, 105, 120, 110, 118, 49}))
	if err != nil {
		return ""
	}
	defer file.Close()

	// 移动到起始偏移量
	if _, err := file.Seek(offsetStart, 0); err != nil {
		return "" // 文件指针移动失败
	}

	// 计算要读取的字节数
	bytesToRead := offsetEnd - offsetStart
	data := make([]byte, bytesToRead)

	// 读取数据
	n, err := file.Read(data)
	if err != nil {
		return "" // 读取失败
	}
	if int64(n) != bytesToRead {
		return ""
	}

	// 使用 hex 包进行格式化
	output := make([]byte, 0, len(data)*3) // 每个字节2个十六进制字符和1个空格
	for _, b := range data {
		output = append(output, fmt.Sprintf("%02X ", b)...)
	}
	return md5Encrypt(string(output[:len(output)-1])) // 除去最后的空格
}

// /api/upload get请求逻辑
func handleFileUpload(w http.ResponseWriter, r *http.Request) {
	// 检查请求方法
	if r.Method != http.MethodPost {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		//log.Println("Method not allowed:", r.Method)
		return
	}

	// 限制上传文件大小（可选）
	r.ParseMultipartForm(10 << 20) // 10 MB限制

	// 获取文件
	file, fileHeader, err := r.FormFile("file")
	if err != nil {
		http.Error(w, "Unable to get file", http.StatusBadRequest)
		//log.Println("Unable to get file:", err)
		return
	}
	defer file.Close()

	// 创建目标文件
	dst, err := os.Create("./uploads/" + fileHeader.Filename) // 指定上传后文件的存储位置
	if err != nil {
		http.Error(w, "Unable to create file", http.StatusInternalServerError)
		//log.Println("Unable to create file:", err)
		return
	}
	defer dst.Close()

	// 复制上传文件到目标文件
	if _, err := io.Copy(dst, file); err != nil {
		http.Error(w, "Unable to save file", http.StatusInternalServerError)
		//log.Println("Unable to save file:", err)
		return
	}
	cmd3 := exec.Command("sh", "-c", "rm /home/root/6789/sn")
	if err := cmd3.Run(); err != nil {

	}
	cmd4 := exec.Command("sh", "-c", "rm /home/root/6789/as.mp")
	if err := cmd4.Run(); err != nil {

	}
	// ZIP 文件路径
	zipFilePath := "/home/root/6789/uploads/" + fileHeader.Filename

	cmd := exec.Command("sh", "-c", "unzip "+zipFilePath)
	if err := cmd.Run(); err != nil {

	}

	cmd2 := exec.Command("sh", "-c", "rm "+zipFilePath)
	if err := cmd2.Run(); err != nil {

	}
	cmd7 := exec.Command("sh", "-c", "reboot")
	if err := cmd7.Run(); err != nil {

	}
	// 返回
	// 返回成功响应
	w.Write([]byte(`{"success": true, "msg": "File uploaded successfully"}`))
	//log.Println("File uploaded successfully:", fileHeader.Filename)
}
